import React, { useState, useEffect } from 'react';
import cookie from 'react-cookies';
import { Head } from 'ice';
import {
  Button,
  Card,
  Dialog,
  Field,
  Form,
  Icon,
  Input,
  Message,
  Pagination,
  Radio,
  ResponsiveGrid,
  Table,
  Upload,
} from '@alifd/next';
import { useFusionTable } from 'ahooks';
import PageHeader from '@/components/PageHeader';
import ossService from '@/services/oss';
import store from '@/store';
import styles from './index.module.scss';

const typeData = [
  { label: '七牛', value: 1 },
  { label: '阿里云', value: 2 },
  { label: '腾讯云', value: 3 },
];

const Oss = () => {
  const [configVisible, setConfigVisible] = useState(false);
  const [type, setType] = useState(0);
  const [loadingConfig, setLoadingConfig] = useState(false);
  const [uploadVisible, setUploadVisible] = useState(false);
  const field = Field.useField();
  const [ossState, ossDispatchers] = store.useModel('oss');
  useEffect(() => {
    ossDispatchers.getConfig();
  }, [ossDispatchers]);

  const { tableProps, paginationProps, search } = useFusionTable(ossService.list, {
    defaultPageSize: 15,
    field,
    cacheKey: 'tableProps',
    formatResult: (response) => {
      return {
        list: response.page.list,
        total: response.page.totalCount,
      };
    },
  });

  const qiniuFormItems = (
    <>
      <Form.Item label="域名" hidden={type !== 1}>
        <Input name="qiniuDomain" disabled={type !== 1} />
      </Form.Item>
      <Form.Item label="路径前缀" hidden={type !== 1}>
        <Input name="qiniuPrefix" disabled={type !== 1} />
      </Form.Item>
      <Form.Item label="AccessKey" hidden={type !== 1}>
        <Input name="qiniuAccessKey" disabled={type !== 1} />
      </Form.Item>
      <Form.Item label="SecretKey" hidden={type !== 1}>
        <Input name="qiniuSecretKey" disabled={type !== 1} />
      </Form.Item>
      <Form.Item label="空间名" hidden={type !== 1}>
        <Input name="qiniuBucketName" disabled={type !== 1} />
      </Form.Item>
    </>
  );

  const aliyunFormItems = (
    <>
      <Form.Item label="域名" hidden={type !== 2}>
        <Input name="aliyunDomain" disabled={type !== 2} />
      </Form.Item>
      <Form.Item label="路径前缀" hidden={type !== 2}>
        <Input name="aliyunPrefix" disabled={type !== 2} />
      </Form.Item>
      <Form.Item label="EndPoint" hidden={type !== 2}>
        <Input name="aliyunEndPoint" disabled={type !== 2} />
      </Form.Item>
      <Form.Item label="AccessKeyId" hidden={type !== 2}>
        <Input name="aliyunAccessKeyId" disabled={type !== 2} />
      </Form.Item>
      <Form.Item label="AccessKeySecret" hidden={type !== 2}>
        <Input name="aliyunAccessKeySecret" disabled={type !== 2} />
      </Form.Item>
      <Form.Item label="BucketName" hidden={type !== 2}>
        <Input name="aliyunBucketName" disabled={type !== 2} />
      </Form.Item>
    </>
  );
  const qCloudFormItems = (
    <>
      <Form.Item label="域名" hidden={type !== 3}>
        <Input name="qcloudDomain" disabled={type !== 3} />
      </Form.Item>
      <Form.Item label="路径前缀" hidden={type !== 3}>
        <Input name="qcloudPrefix" disabled={type !== 3} />
      </Form.Item>
      <Form.Item label="AppId" hidden={type !== 3}>
        <Input name="qcloudAppId" disabled={type !== 3} />
      </Form.Item>
      <Form.Item label="SecretId" hidden={type !== 3}>
        <Input name="qcloudSecretId" disabled={type !== 3} />
      </Form.Item>
      <Form.Item label="SecretKey" hidden={type !== 3}>
        <Input name="qcloudSecretKey" disabled={type !== 3} />
      </Form.Item>
      <Form.Item label="BucketName" hidden={type !== 3}>
        <Input name="qcloudBucketName" disabled={type !== 3} />
      </Form.Item>
      <Form.Item label="Bucket所属地区" hidden={type !== 3}>
        <Input name="qcloudRegion" placeholder="如：sh（可选值 ，华南：gz 华北：tj 华东：sh）" disabled={type !== 3} />
      </Form.Item>
    </>
  );

  const accept = ['image/png', 'image/jpeg', 'image/gif'];

  return (
    <>
      <Head>
        <title>文件上传</title>
      </Head>
      <ResponsiveGrid gap={20}>
        <ResponsiveGrid.Cell colSpan={12}>
          <PageHeader breadcrumbs={[{ name: '系统管理' }, { name: '文件上传' }]} />
        </ResponsiveGrid.Cell>
        <ResponsiveGrid.Cell colSpan={12}>
          <Card free>
            <Card.Content>
              <div className={styles.groupButton}>
                <Button
                  type="primary"
                  onClick={() => {
                    setConfigVisible(true);
                    field.setValues(ossState.config);
                    setType(field.getValue('type'));
                  }}
                >
                  云存储配置
                </Button>
                <Button type="primary" onClick={() => setUploadVisible(true)}>
                  文件上传
                </Button>
                <Button type="primary" warning>
                  批量删除
                </Button>
              </div>
              <Table {...tableProps} primaryKey="id" rowSelection={{}}>
                <Table.Column title="ID" dataIndex="id" width={80} sortable />
                <Table.Column title="URL 地址" alignHeader="center" dataIndex="url" />
                <Table.Column title="创建时间" dataIndex="createTime" width={180} sortable />
                <Table.Column title="操作" dataIndex="id" width={150} align="center" />
              </Table>
              <Pagination style={{ marginTop: '1rem' }} {...paginationProps} />
            </Card.Content>
          </Card>
        </ResponsiveGrid.Cell>
      </ResponsiveGrid>
      <Dialog
        title="云存储配置"
        align="tc tc"
        minMargin={150}
        visible={configVisible}
        okProps={{ loading: loadingConfig }}
        onOk={() => {
          setLoadingConfig(true);
          ossDispatchers.postConfig(field.getValues()).then(() => {
            setConfigVisible(false);
            setLoadingConfig(false);
            ossDispatchers.getConfig();
          });
        }}
        onClose={() => setConfigVisible(false)}
        onCancel={() => setConfigVisible(false)}
        style={{ width: 500 }}
      >
        <Form fullWidth field={field} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
          <Form.Item label="存储类型">
            <Radio.Group name="type" dataSource={typeData} onChange={(value) => setType(value)} />
          </Form.Item>
          {qiniuFormItems}
          {aliyunFormItems}
          {qCloudFormItems}
        </Form>
      </Dialog>
      <Dialog
        title="上传文件"
        align="tc tc"
        minMargin={150}
        visible={uploadVisible}
        footer={false}
        onClose={() => setUploadVisible(false)}
        style={{ width: 500 }}
      >
        <Upload.Dragger
          action="/api/sys/oss/upload"
          listType="image"
          accept={accept.join(', ')}
          multiple
          autoUpload
          headers={{ token: cookie.load('token') }}
          beforeUpload={(file) => {
            if (accept.some((val) => val === file.type)) {
              return true;
            } else {
              Message.error('格式不支持！');
              return false;
            }
          }}
          formatter={(res, file) => {
            return {
              success: res.code === 0,
              message: res.msg,
            };
          }}
          onError={(error) => {
            Message.error(error.error.message);
          }}
        >
          <div className="next-upload-drag">
            <p className="next-upload-drag-icon">
              <Icon type="upload" />
            </p>
            <p className="next-upload-drag-text">点击或者拖动文件到虚线框内上传</p>
            <p className="next-upload-drag-hint">只支持jpg、png、gif格式的图片！</p>
          </div>
        </Upload.Dragger>
      </Dialog>
    </>
  );
};

export default Oss;
